package com.rykj.energy.task.message.construct;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rykj.energy.common.utils.CollectionUtils;
import com.rykj.energy.common.utils.DateUtils;
import com.rykj.energy.common.utils.FileUtils;
import com.rykj.energy.common.utils.StringUtils;
import com.rykj.energy.database.service.IMsgResultService;
import lombok.extern.slf4j.Slf4j;
import net.anumbrella.seaweedfs.core.FileTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 定时清理文件
 */
@Component
@Slf4j
public class CleanFileQuartz {

    @Autowired
    private IMsgResultService resultService ;

    @Autowired
    @Lazy
    private FileTemplate template;

    @Value("${file.upload:/data/rykj-energy/images}")
    private String savePicturePath;

    @Value("${delete.file.beforeDay:3}")
    private  Integer beforDay;

    /**
     * 默认每天临凌晨1点开始清理文件
     */
   // @Scheduled(cron = "${delete.file.cron}")
    public void cleanFiles(){
        log.info("=====开始清理文件===start==");
        String delDate = DateUtils.getDateDay(DateUtils.addHowDay(new Date(),-beforDay));
           // 1.查出所有需要清理的图片，清理文件服务器上的文件

        int i =0;
        Page<Map<String, Object>> page=new Page<>();

        while (true){
            i++;
            page.setCurrent(i);
            page.setSize(2000);
            IPage<Map<String,Object>> pags=resultService.selectImgsByDate(page,delDate);
            List<Map<String,Object>> resultImgs=pags.getRecords();
            if(CollectionUtils.isEmpty(resultImgs)){
                log.info("===清理文件第"+i+"页为空，清理结束===");
                break;
            }
            log.info("=====开始清理文件服务器=="+delDate+"=第="+i+"页==的文件===数量=="+resultImgs.size());
            if(CollectionUtils.isNotEmpty(resultImgs)) {
                //            List<String> imgFileIds =new ArrayList<>();
                //            List<String> cutImgFileIds =new ArrayList<>();
                String imgUrl = "";
                String cutImgUrl = "";
                for (Map<String, Object> imgMap : resultImgs) {
                    imgUrl = imgMap.get("imgUrl") + "";
                    if (StringUtils.isNotEmpty(imgUrl)) {
                        // imgFileIds.add(imgUrl.substring(imgUrl.lastIndexOf("/")+1));
                        try {
                            log.info("=====清理原图文件==imgUrl==" + imgUrl);
                            template.deleteFile(imgUrl.substring(imgUrl.lastIndexOf("/") + 1));
                        } catch (Exception e) {
                            log.error("=====删除文件服务器上" + delDate + "天的文件异常====", e);
                        }
                    }
                    cutImgUrl = imgMap.get("cutImgUrl") + "";
                    if (StringUtils.isNotEmpty(cutImgUrl)) {
                        // cutImgFileIds.add(cutImgUrl.substring(cutImgUrl.lastIndexOf("/")+1));
                        try {
                            log.info("=====开始清理缩略图文件===cutImgUrl==" + cutImgUrl);
                            template.deleteFile(cutImgUrl.substring(cutImgUrl.lastIndexOf("/") + 1));
                        } catch (Exception e) {
                            log.error("=====删除文件服务器上" + delDate + "天的文件异常====", e);
                        }
                    }
                }
            }
        }

              /*  try {
                log.info("=====开始清理原图文件===数量=="+imgFileIds.size());
                template.deleteFiles((ArrayList<String>) imgFileIds);
                log.info("=====开始清理缩略图文件===数量=="+cutImgFileIds.size());
                template.deleteFiles((ArrayList<String>) cutImgFileIds);
            }catch (Exception e){
                log.error("=====删除文件服务器上"+delDate+"天的文件异常====",e);
            }*/

        log.info("=====开始清理临时文件=====");
        //2.根据日期删除  日期目录
        String deleteFile = savePicturePath + File.separator + delDate.replaceAll("-","");
        FileUtils.del(deleteFile);
        log.info("=====开始清理文件===end==");
    }
}
